import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/home";

// 导入 路由实例
import store from "@/store";



Vue.use(VueRouter);

const routes = [{
        path: "/",
        name: "Home",
        component: Home,
        meta: {
            index: 1
        }
    },
    {
        path: "/category",
        name: "Category",
        component: () =>
            import ("../views/category"),
        meta: {
            index: 1
        }
    },
    {
        path: "/shopcar",
        name: "Shopcar",
        component: () =>
            import ("../views/shopcar"),
        meta: {
            index: 1,
            auth: true
        }
    },
    {
        path: "/me",
        name: "Me",
        component: () =>
            import ("../views/me"),
        meta: {
            index: 1,
            auth: true
        }
    },
    {
        path: '/productlist',
        name: 'ProductList',
        component: () =>
            import ('../views/product-list/product-list.vue'),
        meta: {
            index: 2
        }
    },
    {
        path: '/login',
        name: 'Login',
        component: () =>
            import ('@/views/login/login.vue'),
        meta: {
            index: 2
        }
    },
    {
        // /:id 提供id 参数传递
        path: '/detail/:id',
        name: 'Detail',
        component: () =>
            import ('@/views/product-detail/product-detail.vue'),
        meta: {
            index: 3
        }
    },
    {
        path: '/proxy',
        name: 'Proxy',
        component: () =>
            import ('@/views/login/proxy.vue')
    }
];

const router = new VueRouter({
    mode: 'history',
    routes,
});

router.beforeEach((to, from, next) => {
    // 判断当前用户 已登录 再次访问 登录界面 直接跳转到 个人中心页面
    if (to.name === 'Login' && store.getters.getIsLogin) {
        next('/me')
    }
    // console.log('from:', from);
    if (to.meta.auth) { // 需要校验用户是否登录的页面

        // 判断 用户是否登录
        // console.log(store.getters);
        if (store.getters.getIsLogin) {

            // console.log('------');
            next()
        } else {
            // console.log('+++++++');
            // 未登录 跳转到登录页面
            next({ path: '/login' })
        }
    } else {
        next()
    }
})

export default router;